简体   繁体   中英

Backbone/underscore.js json to template with an each loop

I am doing something wrong with backbone and underscore to echo some data in a template.

I have this php file: (test.php)

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

And this template:

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

This is my backbone file:

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);
    }
});

Now for some reason this echo's:

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

so 4 times instead of 1.

And also when I make the json longer like this:

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

It echo's nothing at all. What am I doing wrong. I think I dont understand some stuff but I cant find what.

Hope anyone can help me out!

Greetings, Merijn de Klerk

Your template will work properly if you pass to this.template() a JSON object as follows: $(this.el).html(this.template({'messageView':[{'kroeg':'test 1','locatie':'test 2'},{'kroeg':'test 5','locatie':'test 6'}]}));

That is, _.each() method expects messageView to be an array:

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

First problem in each : it iterate messageView keys, thats why output repeats.

So you have to replace

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

With

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

About "longer json". You are trying to render Collection . You need to send data from PHP as array

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

and create class for collection

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

instance it, fetch and render

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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