using System;
using System.Collections.Generic;
namespace IFramework
{
///
/// ObservableObject 注册监听Helper
///
public class ObservableObjectHandler : Unit
{
struct ObserveEntity
{
private string _propertyName;
private ObservableObject _observableObject;
private Action _listenner;
public string propertyName { get { return _propertyName; } }
public ObservableObject observableObject { get { return _observableObject; } }
public ObserveEntity(ObservableObject obj, string propertyName, Action listenner)
{
this._propertyName = propertyName;
this._observableObject = obj;
this._listenner = listenner;
}
public void Bind()
{
observableObject.Subscribe(propertyName, _listenner);
}
public void UnBind()
{
observableObject.UnSubscribe(propertyName, _listenner);
}
}
internal static ObservableObjectHandler handler { get; private set; }
private List _entitys = new List();
private Action listenner;
internal ObservableObjectHandler Subscribe(ObservableObject _object, string propertyName)
{
Subscribe(_object, propertyName, listenner);
return this;
}
///
/// 对一个 ObservableObject 注册一个监听
///
/// ObservableObject
/// 属性名称
/// 回调
///
public ObservableObjectHandler Subscribe(ObservableObject _object, string propertyName, Action listenner)
{
var bindTarget = new ObserveEntity(_object, propertyName, listenner);
bindTarget.Bind();
_entitys.Add(bindTarget);
return this;
}
///
/// 绑定一个监听
///
/// 回调
///
public ObservableObjectHandler BindProperty(Action setter)
{
this.listenner = setter;
handler = this;
setter.Invoke();
listenner = null;
handler = null;
return this;
}
///
/// 绑定一个监听
///
///
/// 设置值
/// 获取值
///
public ObservableObjectHandler BindProperty(Action setter, Func getter)
{
this.listenner = () => { setter(getter()); };
setter(AddExpressionListener(getter));
return this;
}
private T AddExpressionListener(Func expression)
{
handler = this;
var result = expression.Invoke();
handler = null;
listenner = null;
return result;
}
///
/// 取消所有监听
///
public void UnSubscribe()
{
_entitys.ForEach((entity) =>
{
entity.UnBind();
});
_entitys.Clear();
}
///
/// 取消符合条件的监听
///
/// ObservableObject
/// 属性名称
public void UnSubscribe(ObservableObject _object, string propertyName)
{
var result = _entitys.RemoveAll((entity) =>
{
if (entity.observableObject != _object || entity.propertyName != propertyName) return false;
entity.UnBind();
return true;
});
}
///
/// 释放
///
protected override void OnDispose()
{
UnSubscribe();
}
}
}