简体   繁体   English

骨干视图原型事件绑定

[英]Backbone view prototype event binding

I'm creating a Backbone.js plugin that offers a basic grid layout given supplied JSON data. 我正在创建一个Backbone.js插件,该插件提供了提供的JSON数据的基本网格布局。 My problem is that I'm not sure how to deal with binding events to a View class without altering the plugin itself. 我的问题是我不确定如何在不更改插件本身的情况下处理与View类的绑定事件。 And I'd rather not do this -- I'd rather have the user of the plugin be able to extend the view, or alter its prototype to bind custom events. 而且我宁愿不这样做-我希望插件的用户能够扩展视图或更改其原型以绑定自定义事件。

The View in the plugin is a basic view without any events binded. 插件中的View是一个基本视图,没有绑定任何事件。 It also contains some other functions which I've omitted for simplicity. 它还包含一些其他功能,为简单起见,我已将其省略。

FlipCard.CardView = Backbone.View.extend({

    tagName: 'div',

    className: 'card',

// and more

});

I've attempted to use the prototype attribute in my separate app.js file to bind events, but they don't seem to be triggered. 我试图在单独的app.js文件中使用prototype属性绑定事件,但似乎未触发事件。

FlipCard.CardView.prototype.events = {
    'click .card' : 'alert'
};

FlipCard.CardView.prototype.alert = function(){
    alert("hello!");
};

And I'm familiar with the .extend({}) function, but that won't work unless I can somehow inform the plugin to use the extended version of the view... which I'd rather not do. 而且我熟悉.extend({})函数,但是除非我能以某种方式通知插件使用视图的扩展版本,否则该方法将不起作用...我宁愿不这样做。

Any ideas on what I should be doing here? 关于我应该在这里做什么的任何想法?

EDIT: Turns out it was a silly error. 编辑:原来这是一个愚蠢的错误。 Because the view has the class '.card' and I was trying to bind a click event to '.card', it's unnecessary to put in 'click .card'. 由于视图具有类“ .card”,并且我试图将click事件绑定到“ .card”,因此无需放入“ click .card”。 Instead the event should be: 相反,该事件应为:

FlipCard.CardView.prototype.events = {
    'click' : 'alert'
};

If someone were to use their plugin, they would extend your FlipCard.CardView in the same way you are extending Backbone.Model 如果有人使用他们的插件,他们会延长你的FlipCard.CardView在要扩展以同样的方式Backbone.Model

myApp.Views.myCardView = FlipCard.CardView.extend({
    events: {
        'click .card' : 'alert'
    },
    alert: function() {
        alert("hello!");
    }
}

This creates an extended version of your plugin view with events bound to it, and it does not alter the plugin in any way. 这将创建带有绑定事件的插件视图的扩展版本,并且不会以任何方式改变插件。 The user would then instantiate it as normal: 然后,用户将按常规实例化它:

var someView = new myApp.Views.myCardView();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM