Quantcast
Channel: JavaScriptMVC Forum
Viewing all articles
Browse latest Browse all 3491

Two-level controls+views and live binding?

$
0
0
Hello

I'm exploring with CanJS controls, views and live binding.

I want to create a two-level control structure where I have one ItemsController
that holds multiple ItemController inside:

Here are my EJS templates:

itemsTemplate.ejs :
  1. <% items.each(function(item) { %>
  2.     <div id="itemHolder-<%=item.attr('id') %>"></div>
  3. <% }); %>

itemTemplate.ejs :

  1. <div class="item" <%= (el) -> el.data('item', item) %>>
  2.     <%=item.attr('name') %>
  3. </div>

This is my current structure:

  1. var itemsTemplate = require('text!views/itemsTemplate.ejs');
  2. can.view.ejs('itemsTemplate', exampleTemplate);
  3. var ItemsControl = can.Control({

  4.     init: function(el, options) {

  5.         can.view('itemsTemplate', {items: options.items}, function(template){
  6.             that.element.html(template);

  7.             // Create items into itemHolder "sandboxes"
  8.             $.each(options.items, function(key, item){
  9.                 var itemControl = new ItemControl('#itemHolder-'+item.attr('id'), {item: item});
  10.             }
  11.         });
  12.     },

  13.     destroy: function() {
  14.         console.log('destroy called for ItemsControl');
  15.         can.Control.prototype.destroy.call( this );
  16.     }
  17. });


  18. var itemTemplate = require('text!views/itemTemplate.ejs');
  19. can.view.ejs('itemTemplate', itemTemplate);

  20. var ItemControl = can.Control({

  21.     init: function(el, options) {
  22.         can.view('itemTemplate', {item: options.item}, function(template){
  23.             that.element.html(template);
  24.         });
  25.     },

  26.     destroy: function() {
  27.         console.log('destroy called for ItemControl');
  28.         can.Control.prototype.destroy.call( this );
  29.     },

  30.     'click': function() {
  31.         console.log('You clicked item!');
  32.     }
  33. });

  34. // Testing
  35. var testItems = new can.List();
  36. testItems.push({id: 1, name: 'Item #1'});
  37. testItems.push({id: 2, name: 'Item #2'});
  38. testItems.push({id: 3, name: 'Item #3'});

  39. // Render test items
  40. var testItemsControl = new ItemsControl('#items', {items: testItems});


This seems to work well on init but when I later push new item to testItems, all 3 existing items completely dissappear from the view and ItemControl.destroy gets called 3 times.

Could someone give me an example how to do this two-level control structure so that it works well with live binding?


Viewing all articles
Browse latest Browse all 3491

Trending Articles