2

The code is from Addy Osmani: Learning JavaScript Design Patterns, and I didn't really get the implementation.

I may be blind here, but I can't see what's wrong with this:

ReferenceError: Can't find variable: items

Underscore template:

<script id="resultTemplate" type="text/html">
    <% _.each(items, function( item ){  %>
            <li><p><img src="<%= item %>"/></p></li>
    <% });%>
</script>

jQuery:

var resultTemplate = _.template($("#resultTemplate").html());

[...]

Demo: jsFiddle

2
  • Where you defined items? Commented Jul 2, 2013 at 14:46
  • Returned from Flickr, see fiddle Commented Jul 2, 2013 at 22:14

2 Answers 2

2
+50

Short answer: it's not really easy/convenient to pass array as argument using this Tiny Pub/Sub plugin.

You can check the documentation here https://gist.github.com/cowboy/661855. As you can see, on $.subscribe() part, the array element can only be passed one by one, so in your example it could work this way:

$.subscribe("/search/resultSet" , function(e, item1, item2, item3){
    $("#searchResults").append(resultTemplate(item1));
    $("#searchResults").append(resultTemplate(item2));
    $("#searchResults").append(resultTemplate(item3));
    // and so on
});

... and the template should updated accordingly.

Of course this is not convenient at all. I suggest you google for another plugin that supports Pub/Sub pattern (if you still want to use it), if you don't want to do an ugly workaround for the current one. Another source I found is: Passing arrays via jQuery tiny PubSub

Hope this helps ;)

Sign up to request clarification or add additional context in comments.

Comments

0

This works:

// Subscribe to the new results topic
$.subscribe( "/search/resultSet" , function( e, results ){

    $( "#searchResults" ).append(resultTemplate( {items: results} ));

});

_.template() explodes the object that you pass to it. So instead of passing the results object, pass an object containing an items object made up of the results. The template explodes this and is able to iterate over the items.

See: http://jsfiddle.net/nmBGC/2/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.