骨干网ID和点击事件 [英] Backbone Model Ids and on click events

查看:59
本文介绍了骨干网ID和点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的.我要在这里让步并寻求帮助.我认为我遇到了多个问题,不确定最好的方法.我正在使用车把来创建ul li,这是我对主干模型的json对象.现在,该模板可以使用了,我想要单击该模型,以能够将其添加到另一个集合中.

Alright. I'm going to give in here and ask for some help. I think I'm running into multiple issues and not sure of the best approach. I'm using handlebars to create an ul of li that are my json objects to backbone models. Now that the template works I want to on click get the model to be able to add to another collection.

我的第一个问题.我认为主干默认情况下定义了模型ID?如果我将default设置为"或null,则每个模型的id均为"或null. json对象具有一个我可以分配给主干ID的ID,但是如果我在默认ID中执行该操作:jsonID,则jsonID是未定义的.如果我在控制台中执行object.toJSON(),则不会创建任何主干ID.因此,我没有在把手模板中使用的值来将我的div ID分配给该模型的主干ID.然后使用它来获取元素ID,以便在单击时可以获取主干ID.或者至少我已经阅读了很多这样做的示例.

My first problem. I thought backbone defined a model id by default? If i set default to "" or null every model's id is "" or null. The json objects have an id I could assign to the backbone id but if I do that in the defaults id: jsonID, the jsonID is undefined. If I do object.toJSON() in the console there is no backbone created id. So I don't have a value to use in the handlebars template to assign my div id to the backbone id for that model. To then use that to get element id so that on click I could get the backbone id. Or at least I've read a lot of examples that do it that way.

我的第二个问题,我认为源于requirejs.我看到的所有示例都使用了this.collection或this.model.在我的View文件中,这些总是返回undefined,假设这是由于requirejs引起的.我特别尝试了此示例

My second issue, I think stems from requirejs. All the examples I see for click even use this.collection or this.model. On my View file those always return undefined, assuming this is because of requirejs. I tried this example in particular http://lostechies.com/derickbailey/2011/10/11/backbone-js-getting-the-model-for-a-clicked-element/. I'm wondering if I should just scrap using requirejs, it seems to cause more problems then help.

到目前为止,这是我的代码,由于没有任何作用,因此删除了我的点击功能代码.

Here is my code so far, I deleted out my click function code because none of it was working.

收集文件:

define(['jquery', 'backbone', 'lodash', 'Models/GroceryItem'],

    function($, Backbone, _, GroceryItem) {

    var GroceryItems = Backbone.Collection.extend({

        model: GroceryItem,

        url: "data.json",

        parse: function(response) {
            return response.all_coupons;

        }

    });

    var storeItems = new GroceryItems();
    storeItems.fetch({
    success:function(){
        console.log(storeItems.toJSON());
        }
    });

    return storeItems;

});

查看文件:

define(['jquery', 'backbone', 'lodash', 'handlebars', 'Collections/GroceryItems'],

    function($, Backbone, _, Handlebars, storeItems) {



    var GroceryItemsView = Backbone.View.extend({

        template: Handlebars.compile(
            '<ul class="d-row">' +
                    '{{#each storeItems}}' +
                        '<li class="lineItem" id="{{coupon_id}}">' +    
                            '<div class="wrapper">' +
                                '<div class="header">{{coupon_title}}</div>' +              
                                    '<div class="column_wrapper">' +
                                        '<div class="two-col">' +
                                            '<div class="product_image"><img src="{{coupon_thumb}}" alt="{{coupon_description}}" height="110" width="110"></div>' +
                                            '<div class="description">{{coupon_description}}</div>' +
                                         '</div>' +
                                    '</div>' +
                                '<div class="expiration">Valid From: {{valid_from}} to {{valid_to}}</div>' +    
                            '</div>' +
                        '</li>' +
                '{{/each}}' +
            '</ul>'
            ),

        events: {
            "click li": "getModel"
        },

        getModel:function(e){

        },

        render: function() {
            var that = this;
            storeItems.fetch({
                success: function(storeItems) {
                    var storeTemplate = that.template({storeItems: storeItems.toJSON()});
                    that.$el.html(storeTemplate);
                    return that;
                }
            })          
            return this; 
        }
    });

    return GroceryItemsView;

});

非常感谢您的帮助.非常感谢.如果我要彻底解决这个问题,欢迎提出任何建议.我只是一般地学习骨干和javascript,因此在进行大量的谷歌搜索时我会逐渐疲倦.

Thanks a bunch for any help. It's much appreciated. If I'm going at this completely wrong, I'm open to any suggestions. I'm just learning backbone and javascript in general so I'm grinding away as I go with a lot of googling.

谢谢!

编辑代码:

define(['jquery', 'backbone', 'lodash', 'Collections/GroceryItems', 'Views/GroceryItemView'],

    function($, Backbone, _, storeItems, GroceryItemView) {

    var GroceryItemsView = Backbone.View.extend({

        tagName: 'ul',
        className: 'd-row',
        el: '#container',
        initialize: function () {
            //basically says only render when collection syncs
            this.listenTo(storeItems, 'sync', this.render);
        },

        render: function () {
            //got keep track of views for when you need close them (not important for now but you'll thank me later)
            this.groceryItemsView = [];
            storeItems.each(function (GroceryItem) {
                //we are making a new view for each model and passing it in as an option
                var itemView = new GroceryItemView({
                    model: GroceryItem
                });
                //The view creates an element but it is not attached to DOM. We will attach it to the ItemsView's $el (which IS attached to the DOM)
                this.$el.append(itemView.$el);

                this.groceryItemsView.push(itemView);
            }, this);
            }
        });

    var list = new GroceryItemsView();

    return list;

});

define(['jquery', 'backbone', 'lodash', 'handlebars', 'Views/GroceryItemsView', 'Models/GroceryItem'],

    function($, Backbone, _, Handlebars, GroceryItemsView, GroceryItem) {

        var GroceryItemView = Backbone.View.extend({

        template: Handlebars.compile(
            '<div class="wrapper">' +
                '<div class="header">{{coupon_title}}</div>' +
                    '<div class="column_wrapper">' +
                        '<div class="two-col">' +
                            '<div class="product_image"><img src="{{coupon_thumb}}" alt="{{coupon_description}}" height="110" width="110"></div>' +
                            '<div class="description">{{coupon_description}}</div>' +
                        '</div>' +
                    '</div>' +
                '<div class="expiration">Valid From: {{valid_from}} to {{valid_to}}</div>' +
            '</div>'
        ),

        tagName: 'li',

        className: 'lineItem',

        events: {
            'click': 'getModel'
        },

        initialize: function () {
           this.render();
        },

        getModel: function () {
            return this.model;
        },

        render: function () {
            this.$el.html(this.template(this.model.toJSON()));
        }
    });

    return GroceryItemView;
});

推荐答案

获得所单击对象模型的最简单方法非常简单.

The easiest way to get to a model of something you clicked is surprisingly simple.

  1. 我强烈建议您不要依赖ID.这是非常糟糕的做法.使用模型的全部目的是不再担心IDs:P
  2. 创建骨干网视图并不像某些人所说的那样昂贵.只要您正确清理,它实际上是非常有效的.将DOM的每个逻辑单元分解为自己的视图.尤其是视图集合
  3. 需求真是棒极了.不要放弃.一旦弄清楚了,就再也回不去了.只需将其视为将一堆代码从另一个文件保存到顶部定义的变量
  4. 不要使用success选项.只听sync事件.使代码更整洁,防止以后再出现怪异的问题.
  1. I STRONGLY recommend NOT relying on IDs. It's very bad practice. The whole point of using Models is to stop worrying about IDs :P
  2. Creating a Backbone View is not as expensive as some people say. It's actually quite efficient as long as you clean up properly. Break up every logical unit of DOM into it's own View. ESPECIALLY collections of Views
  3. Require is AWESOME. Don't give up on it. Once you figure it out you'll never want to go back. Just think of it as saving bunch of code from another file to a variable defined up top
  4. Don't use success option. Only listen to the sync event. Makes code cleaner, prevents loooooots of weird issues later on.

我还没有测试这段代码,但是逻辑工作正常(已经做了很多次)

I haven't tested this code but the logic works (have done it many times)

//Preferrably keep this in a separate file or use require-handlebars
var itemTpl = Handlebars.compile(
    '<div class="wrapper">' +
    '<div class="header">{{coupon_title}}</div>' +
    '<div class="column_wrapper">' +
    '<div class="two-col">' +
    '<div class="product_image"><img src="{{coupon_thumb}}" alt="{{coupon_description}}" height="110" width="110"></div>' +
    '<div class="description">{{coupon_description}}</div>' +
    '</div>' +
    '</div>' +
    '<div class="expiration">Valid From: {{valid_from}} to {{valid_to}}</div>' +
    '</div>');

//Your Collection
var GroceryItems = Backbone.Collection.extend({

    model: GroceryItem,

    url: "data.json",

    parse: function (response) {
        return response.all_coupons;
    }

});

//This Represents all your views
var ItemsView = Backbone.View.extend({
    tagName: 'ul',
    el: '.where-this-is-supposed-to-go',
    initialize: function () {
        this.collection = new GroceryItems();
        //basically says only render when collection syncs
        this.listenTo(this.collection, 'sync', this.render);
    },

    render: function () {
        //got keep track of views for when you need close them (not important for now but you'll thank me later)

        this.itemViews = [];
        this.collection.each(function (m) {
            //we are making a new view for each model and passing it in as an option
            var itemView = new ItemView({
                model: m
            });

            //The view creates an element but it is not attached to DOM. We will attach it to the ItemsView's $el (which IS attached to the DOM)
            this.$el.append(itemView.$el);

            this.itemViews.push(itemView);
        }, this);
    }
});

var ItemView = Backbone.View.extend({
    template: itemTpl,
    tagName: 'li',
    className: 'lineItem',
    events: {
        'click': 'getModel'
    },
    initialize: function () {
       this.render();
    },
    getModel: function () {
        //it's already there. No IDs
        return this.model;
    },
    render: function () {
        this.$el.html(this.template(this.model.toJSON()));
    }
});

这篇关于骨干网ID和点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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