Backbone / underscore.js json到每个循环的模板

时间:2015-09-08 16:42:23

标签: javascript json backbone.js underscore.js

我在使用骨干和下划线做错了,以便在模板中回显一些数据。

我有这个php文件:(test.php)

<?php
echo '{"data1":"test 1","data2":"test 2"}';
?>

这个模板:

<script type="text/template" id="tpl-hello-backbone">
    <% _.each(messageView, function(messageView) { %>
        <%= kroeg %> 
        <%= locatie %>
    <% }); %>
</script>

这是我的骨干文件:

var MessageModel = Backbone.Model.extend({
    urlRoot : 'test.php'
});

var MessageView = Backbone.View.extend({

    template:_.template($('#tpl-hello-backbone').html()),

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

var messageModel = new MessageModel();
var messageView = new MessageView({model:messageModel});
messageModel.fetch({
    success: function () {
        $('#msg').html(messageView.render().el);
    }
});

现在由于某种原因,这个回声是:

 test 2 test 1 test 2 test 1 test 2 test 1 test 2 test 1

所以4次而不是1次。

当我把json变得更长时间时:

<?php
echo '{"kroeg":"test 1","locatie":"test 2"},{"kroeg":"test 1","locatie":"test 2"}';
?>

它回音什么都没有。我究竟做错了什么。我想我不懂一些东西,但我找不到。

希望有人能帮助我!

问候, Merijn de Klerk

2 个答案:

答案 0 :(得分:1)

如果您传递给this.template() JSON对象,您的模板将正常工作,如下所示: $(this.el).html(this.template({'messageView':[{'kroeg':'test 1','locatie':'test 2'},{'kroeg':'test 5','locatie':'test 6'}]}));

也就是说,_.each()方法期望messageView是一个数组:

<script type="text/template" id="tpl-hello-backbone">
    <% _.each(messageView, function(messageView) { %>
        <%= messageView.kroeg %> 
        <%= messageView.locatie %>
    <% }); %>
</script>

答案 1 :(得分:0)

each中的第一个问题:它迭代messageView个键,这就是输出重复的原因。

所以你必须替换

<% _.each(messageView, function(messageView) { %>
    <%= kroeg %> 
    <%= locatie %>
<% }); %>

<%= kroeg %> 
<%= locatie %>

关于“更长的json”。您正尝试呈现集合。您需要从PHP发送数据作为数组

<?php
    echo '[{"kroeg":"test 1","locatie":"test 2"},{"kroeg":"test 1","locatie":"test 2"}]';
?>

并为集合创建类

var MessageCollection = Backbone.Collection.extend({
    model: MessageModel
});

实例,获取和render