Change div ( represent object element ) background color when change element status
How to implement observ开发者_C百科er pattern in Javascript or Dojo. I have created class with Dojo
dojo.declare("ELEMENT", null, {
_id:0,
_status:''
constructor: function(id,status){
this.id=id;
this.status=status;
},
get_color:function(){
},
set_status:function(st){
this._status=st;
}
}
});
and I create div with the same id like element. I want to change color of div background when I change status of element. How to implement this, is there observer for this problem ?
Use Dojo 1.6. Dijit's has a new "watch" functionality that does what you want nicely. It allows other objects (i.e. the observers) to dynamically add callbacks which will be triggered when properties in the class change.
However, you really don't want an observer pattern. What you want is to do something when status is set on your class. This is deterministic; you are not saying that an arbitrary number of observer objects are now interested in what status is set to.
In this case, you can simly define an "_attributeMap" in the class, which autotically maps certain properties/attributes to attributes of DOM elements inside that class. In your example, you can declare and attribute map on the status attribute mapping to the style of the class.
You can also provide a _setXxxAttr function to add more functionalities instead of straight mapping.
Your example is not proper Dojo. It should be this:
dojo.declare("ELEMENT", null, {
id: 0,
status: '',
/*constructor: no need. automatic.*/
_setStatusAttr: function(value) {
this.status = value;
dojo.style("someDomNode", "background-color", value === 'foo' ? "yellow" : "blue");
}
});
var newelement = new ELEMENT({id:123, status:'hello'});
newelement.get("id"); // Get id = 123
newelement.set("status", 'foo'); // Set status to 'foo'. _setStatusAttr is automatically run.
newelement.get("status"); // Get status = 'foo'
In Dojo lingo, _setXxxAttr
automatically redirects on the set("xxx", value)
call.
精彩评论