事件绑定到在下划线/骨干动态对象 [英] binding events to dynamic objects in underscore/backbone

查看:205
本文介绍了事件绑定到在下划线/骨干动态对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出如何监听自定义事件上的underscore.js / Backbone.js的没有原型或者不DOM对象的对象。

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.

例如:

//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]
},

和错误是:

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?

非常感谢
A

Thanks very much A

推荐答案

如果您要绑定到一个对象,你需要使它延长从Backbone.Events对象。

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

假设你创建新的对象。

var o = {};

您不能绑定到它, o.bind()不存在

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

除非你backbone.Events扩展。

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.

这也是(使用你的应用程序创建一个全球性的事件聚集,在他的职位由德里克·贝利描述的技术<一个href=\"http://lostechies.com/derickbailey/2011/07/19/references-routing-and-the-event-aggregator-coordinating-views-in-backbone-js/\" rel=\"nofollow\">http://lostechies.com/derickbailey/2011/07/19/references-routing-and-the-event-aggregator-coordinating-views-in-backbone-js)

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)

这篇关于事件绑定到在下划线/骨干动态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆