binding events to dynamic objects in underscore/ba

2019-08-04 05:46发布

问题:

I'm trying to figure out how to listen for custom events on objects which have not been prototyped or are not dom objects in underscore.js/backbone.js.

for example:

//this is inside a view object
play: function(arg)
{
    this.a  = this.image(this.model.a);
    this.a.bind("ready",start,this);//<--- causes error
    this.b  = this.image(this.model.b);
    this.b.bind("ready",start,this);//<--- causes error
    function start()
    {
        // do some stuff in here
    }
    //some more stuff

},
image: function(args)
{
    // load the image, get its data, attach to original model then return it.
    var args    = args;
    var img     = $("<img/>");
    var t       = this;
    img.load(function(){
        t.pasteboard.drawImage(this,0,0);
        args.imageData = t.pasteboard.getImageData(0,0,args.width,args.height);
        args.ready = true;
        args.trigger("ready",args);
    }).attr("src",args.src).hide();
    return args;
},

and the model looks roughly like this:

a:{
    src:"/img/a.jpg",
    width:1320,
    height:639,
    x:0,
    y:0,
    opactiy:0,
    scale:[1,1]
},
b:{
    src:"/img/b.jpg",
    width:1320,
    height:639,
    x:0,
    y:0,
    opactiy:0,
    scale:[1,1]
},

and the error is:

Uncaught TypeError: Object #<Object> has no method 'bind'

of course it makes sense that theres no bind on the object but has anyone got a good solution for this?

Thanks very much A

回答1:

if you want to bind to an object, you will need to make it extend from the Backbone.Events object.

lets say you create a new object

var o = {};

you can't bind to it, o.bind() does not exist

unless you extend from backbone.Events.

var o = _.extend({}, Backbone.Events);

o.bind('myCustomEvent', function(){
    alert('triggered!');
});

o.trigger('myCustomEvent');

i'm not sure what this means on performance if you want to start binding to hundreds of objects. so you should test around with this before just using it.

this is also the technique used to create a global event Aggregator in your app, as described by Derick Bailey in his post (http://lostechies.com/derickbailey/2011/07/19/references-routing-and-the-event-aggregator-coordinating-views-in-backbone-js)