如何将接收到的数组传递给下划线模板

时间:2016-11-08 13:21:48

标签: javascript backbone.js underscore.js

我从PHP中获取了一个包含各种数据对象的长数组。

[{"commid":"1","uid":"0","pid":"3","comment":"comm","parid":null,"date":"2016-10-27 15:03:10"},
{"commid":"2","uid":"0","pid":"10","comment":"Ana","parid":null,"date":"2016-10-27 15:03:51"},
{"commid":"3","uid":"0","pid":"5","comment":"asss!","parid":null,"date":"2016-10-27 15:05:50"},
{"commid":"4","uid":"0","pid":"10","comment":"Lawl?","parid":null,"date":"2016-10-27 17:03:59"},
{"commid":"5","uid":"0","pid":"14","comment":"sd","parid":null,"date":"2016-11-06 00:25:04"},
{"commid":"6","uid":"0","pid":"14","comment":"sds","parid":null,"date":"2016-11-06 00:25:50"},
{"commid":"7","uid":"0","pid":"14","comment":"WOW!","parid":null,"date":"2016-11-08 15:06:18"},
{"commid":"8","uid":"0","pid":"13","comment":"Hello!?","parid":null,"date":"2016-11-08 15:14:30"}] 

将呈现数据的我的骨干视图

var WorkPage = Backbone.View.extend({
    el: $('#indexcontent'),
    render: function() {
        Backbone.history.navigate('work');
        var _this = this;

        this.$el.html(workHTML);
        $.ajax({
            type: "GET",
            url: "includes/server_api.php/work",
            data: '',
            cache: false,
            success: function(html) {
                console.log(html);
                var compiledTemplate = _.template($('#content-box').html(), html);
                _this.$el.html(compiledTemplate);
            },
            error: function(e) {
                console.log(e);
            }
        });
        return false;
    }
});

我的workHTML将由Underscore呈现

<script type="text/template" id="content-box">
<div class="workhead">
    <h3 class="msg comment"><%= comment%></h3>
    <p class="date"><%= date%></p>
</div>
</script>
<div id="content-box-output"></div>

如何在此处实现下划线循环?

3 个答案:

答案 0 :(得分:2)

在index.html文件中,您需要使用import numpy as np x = np.array([ 1, 2, 3, 4, 5, 6, 7, 8 ,9, 10 ]) y = np.array([ 50 ]) for i in np.arange(len(x)): y = np.append( y, ( y[-1] * 2 + x[i] ) ) y = y[1:] print(y) 方法来迭代每个元素

_.each()

我为您的回复添加变量只是为了让数据可以使用。在您的视图中,您需要在模板上设置点 <% _.each(obj, function(elem){ %> <div class="workhead"> <h3 class="msg comment"><%= elem.comment %></h3> <p class="date"><%= elem.date%></p> </div> <% }) %> ,并且在render方法中只将数据作为对象发送。

以下是工作代码:jsFiddle

答案 1 :(得分:2)

您应该利用Backbone的功能。要做到这一点,您需要了解如何在Backbone中使用REST API。

Backbone's Model用于管理单个对象并处理与API的通信(GETPOSTPATCHPUT请求。< / p>

Backbone's Collection角色是处理模型数组,它处理获取它(GET请求应返回JSON对象数组)并且它还默认将每个对象解析为Backbone模型。

使用Backbone集合,而不是对jQuery ajax调用进行硬编码。

var WorkCollection = Backbone.Collection.extend({
    url: "includes/server_api.php/work",
});

然后,模块化你的观点。为您收到的数组的每个对象创建一个项目视图。

var WorkItem = Backbone.View.extend({
    // only compile the template once
    template: _.template($('#content-box').html()),
    render: function() {

        // this is how you pass data to the template
        this.$el.html(this.template(this.model.toJSON()));

        return this; // always return this in the render function
    }
});

然后您的列表视图如下所示:

var WorkPage = Backbone.View.extend({
    initialize: function(options) {
        this.itemViews = [];
        this.collection = new WorkCollection();

        this.listenTo(this.collection, 'reset', this.render);

        // this will make a GET request to
        // includes/server_api.php/work
        // expecting a JSON encoded array of objects
        this.collection.fetch({ reset: true });
    },
    render: function() {
        this.$el.empty();
        this.removeItems();
        this.collection.each(this.renderItem, this);
        return this;
    },

    renderItem: function(model) {
        var view = new WorkItem({
            model: model
        });
        this.itemViews.push(view);
        this.$el.append(view.render().el);
    },
    // cleanup to avoid memory leaks
    removeItems: function() {
        _.invoke(this.itemViews, 'remove');
        this.itemViews = [];
    }

});

在渲染功能中设置url是不常见的,你应该将责任限定在正确的位置。

路由器可能是这样的:

var Router = Backbone.Router.extend({
    routes: {
        'work': 'workPage'
    },

    workPage: function() {
        var page = new WorkPage({
            el: $('#indexcontent'),
        });
    }
});

然后,如果你想看工作页面:

var myRouter = new Router();

Backbone.history.start();

myRouter.navigate('#work', { trigger: true });

模板和RequireJS

  

我的index.html页面包含此内容   indexcontent div,但content-box包含模板   我们正在编译的格式存储在不同的work.html中。所以,   如果我不加载work.html我的主index.html我无法加载content-box   访问define([ 'underscore', 'backbone', 'text!templates/work-item.html', ], function(_, Backbone, WorkItemTemplate) { var WorkItem = Backbone.View.extend({ template: _.template(WorkItemTemplate), /* ...snip... */ }); return WorkItem; });

我建议使用text require.js plugin并为视图加载每个模板,如下所示:

work-item.js文件:

define([
    'underscore', 'backbone',
    'text!templates/work-page.html',
], function(_, Backbone, WorkPageTemplate) {
    var WorkPage = Backbone.View.extend({
        template: _.template(WorkPageTemplate),
    });
    return WorkPage;
});

work-page.js文件:

{{1}}

答案 2 :(得分:0)

以下是为数据数组中的每个值加载模板的一种方法。

var WorkPage = Backbone.View.extend({
    el: $('#indexcontent'),
    render: function() {
        Backbone.history.navigate('work');
        var _this = this;

        this.$el.html(workHTML);
        $.ajax({
            type: "GET",
            url: "includes/server_api.php/work",
            data: '',
            cache: false,
            success: function(data) {
                console.log(data);
                var $div = $('<div></div>');
                _.each(data, function(val) {
                    $div.append(_.template($('#content-box').html(), val));
                });
                _this.$el.html($div.html());
            },
            error: function(e) {
                console.log(e);
            }
        });
        return false;
    }
});