Reputation: 771
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
Upvotes: 2
Views: 471
Reputation: 5016
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/
Upvotes: 0
Reputation: 8623
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 ;)
Upvotes: 2