【问题标题】:Backbone View triggered by multiple outside elements由多个外部元素触发的主干视图
【发布时间】:2012-10-25 00:58:13
【问题描述】:

我是 Backbone 的新手,想了解我应该如何处理这个问题。我可能在这里没有使用正确的定义 - 提前抱歉!

目前我有一排元素,每个元素都有一个按钮(我将这些按钮称为按钮 A)。这些行是作为 Rails 部分生成的。该按钮会打开一个弹出框,其中包含一些特定于该信息行的控件。代码方面,每次点击任何一个按钮 A 时,只有一个弹出框会自行调整 + 信息,它位于 index.html.erb 文件中。

我想将这些代码转换为 Backbone 视图对象 - 但我不知道如何使弹出框视图与多个按钮交互。

解决这个问题的正确方法是为每个按钮创建一个弹出框并让多个弹出视图相互通信吗?什么是正确的方法?

目前,这些元素都不是主干视图对象。

提前谢谢你。

【问题讨论】:

    标签: javascript ruby-on-rails backbone.js backbone-views backbone-events


    【解决方案1】:

    我假设:

    • 您指的是模式弹出框,而不是弹出窗口。如果您尝试更改弹出窗口的内容,您只需加载一个显示您期望的数据的新 URL。
    • 您的 Rails 模板已经创建了所有 HTML 标记
    • 你正在使用 jQuery

    JSFiddle 示例:http://jsfiddle.net/4J6fL/

    第一步是创建一个负责数据列表功能的Backbone.View 实例。

    var DataView = Backbone.View.extend({
        events: {
            // this event will be bound to every button inside our parent element
            "click button": "enlarge"
        },
    
        enlarge: function(e) {
            // backbone rebinds 'this' to refer to the View. It will not refer to the element 
            // triggering the event as it would in jQuery. Grab a reference to the triggering element.
            $el = $(e.currentTarget);
    
            // gather the data for our popup window
            var popupData = {
                title: $el.siblings('p').text(),
                img: $el.siblings('img').attr('src')
            };
    
            this.popup(popupData);
        },
    
        popup: function(data) {
            // find the view's popup box element - this.$el refers to the views bound DOM element
            var $enlarged = this.$el.find('#enlarged');
    
            // create new elements based on the data
            var $title = $('<h2 />', { text: data.title });
            var $img = $('<img />', { src: data.img });
    
            // empty the popup box of current data
            $enlarged.html('');
    
            // fill the popup box with our new data
            $enlarged.append($title);
            $enlarged.append($img);
        }
    });
    

    此时,我们有一个可以绑定到任何 DOM 元素的视图,并赋予它上述功能。

    • events 属性负责将事件回调绑定到视图。
    • 请注意回调中this 的上下文,Backbone 将其绑定到视图,而不是事件。
    • this.$el 指的是绑定到我们视图的 DOM 元素。您将看到如何做进一步的事情。
    • 实际的弹出逻辑是标准的 jQuery DOM 操作。

    现在我们有了视图,我们需要初始化并使用它。这是在充当控制器的 Backbone.Router 中完成的:

    dataView = new DataView({ el: $('#data-view') });
    

    注意我们如何传递将绑定到此视图的元素 (el)?这就是将 DOM 元素绑定到我们的视图的原因,允许我们在视图中对其进行操作。

    下一个合乎逻辑的步骤是将弹出代码分离到另一个视图中,使用events 表示何时应该更新它。这将使您可以轻松地从页面的其他区域触发弹出窗口。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-31
      相关资源
      最近更新 更多