开发者

Observer in Dojo or Javascript

How to implement observer patter开发者_如何转开发n in Dojo or Javascript ?


Though I'm not sure whether its a direct implementation of Observer Pattern, Dojo Toolkit already has in-built event system.

Dojo Connect: dojo.connect could be both used to connect DOM events to their handlers or could be used to wire-up any function to any other function.

dojo.connect(obj, event, context, method);

Publish/Subscribe: Dojo's Publish/Subscribe could be used to define app-wide topics and then attach/detach handlers to them.

dojo.subscribe(topic, method);
dojo.publish(topic, parameters);

Links:

  • http://docs.dojocampus.org/quickstart/events
  • http://docs.dojocampus.org/dojo/connect
  • https://www.ibm.com/developerworks/web/library/wa-dojoconnect/

Both of these techniques, returns a token which could be used to disconnect the handlers.


In Dojo it is very easy.

  1. dojo.connect will allow you to add a callback on any function of any object.
  2. dijit, Dojo's UI system, has a watch method to add a callback for any property change.

Now, in pure JavaScript, it is more involved, because you cannot trigger a callback for any arbitrary property update on any arbitrary object. You can only "hijack" a property function so that it points to a new function, and that function does your callback after calling the original function. However, you're essentially reimplementing dojo.connect so mind as well just go with Dojo.

Therefore, the observer pattern can only be implemented for function calls in JavaScript.


I found an observer pattern for javascript in these slides http://www.slideshare.net/rmsguhan/javascript-design-patterns on slide 31.

I've typed it up here

// The Observer Object - One who super sees all the print operations
function printManager(){
    var queue = [];

    //The attach method
    this.addJob = function(name, job){
        queue.push({"name":name,"job":job});
    }

    //the detach method
    this.removeJOb = function(job){
        var _queue = [];
        for(var i in queue){
            if(queue[i].job == job)
                continue;
            else
                _queue.push(queue[i]);
        }
        queue = _queue;
    } ...

I made a modified version of this (specific to my use) and it worked fine. It was a good starting point for me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜