2011-04-10 79 views
5

我想创建一个可以移动和调整大小的div,并将它们的width,height等绑定到数组中的对象。所以,如果我创建六个div,我的阵列中有六个对象,每个对象都有.width,.height等。如何绑定div宽度/高度以形成字段?

我不太了解如何将输入和跨度文本绑定到数组对象属性knockout.js。这里是我的尝试:

var counter = 0; 
var objects = []; 

$(document).ready(function() { 
    dostuff($("#main")); // give it a target container div 
}); 

function dostuff(target) { 
    counter++; 
    // create a div containing a span and an input that binds to knockout.js 

    target.append('<div id="d' + counter + '">width:<span id="d' + counter + 
     '" data-bind="text:objects[' + counter + '].width"></span>' + 
     '<input type="text" id="d' + counter + 
     '" data-bind="value:objects[' + counter + '].width"/></div>'); 

    var a = $("#d" + counter); 
    a.css("position", "absolute"); 
    a.css("width", "100px"); 
    a.css("height", "100px"); 
    a.css("background-color", "#" + 
     Math.ceil(Math.random()*9) + "0" + 
     Math.ceil(Math.random()*9) + "0" + 
     Math.ceil(Math.random()*9) + "0"); 
    a.resizable({ 
     stop: function (e, ui) { 
      this.childNodes[2].value = ui.size.width; 
     } 
    }); 
    objects[counter] = { width: "100px", height: "100px", 
     top: "0px", left: "0px" }; 
    ko.applyBindings(objects[counter]); 
} 

我该如何获得objects[1].width绑定到div D1的<input>价值?

回答

4

变化的最小量,你将不得不作出让这种情况发生会做这样的事情:

target.append('<div id="d' + counter + '" data-bind="style: { width: width , height: height, top: top, left: left } }">width:<span id="d' + counter + 
     '" data-bind="text: width"></span>' + 
     '<input type="text" id="d' + counter + 
     '" data-bind="value: width"/></div>'); 

所以,这里使用了style在您的主要DIV结合。此外,由于您正在对对象[counter]调用applyBindings,因此可以直接在绑定中引用属性(而不是通过对象[counter])。

如果您多次调用此函数,那么您将需要小心如何调用ko.applyBindings。如果您没有传递第二个参数,那么它将应用于整个文档。你真的只想这样做一次。在你的情况下,你可能想要传递第二个参数来指示开始的确切根元素。所以,你会打电话给我一些像ko.applyBindings(objects[counter], $("#d" + counter)[0]);

我不知道你的确切用例,但如果是我,我会先创建我的数组对象,然后使用模板来构建div。然后,在标记中,我将有一个容器,它调用template绑定,并通过foreach选项传递数组。然后,您将创建一个包含每个div的标记的模板。这样可以避免将标记构建为字符串。如果你想要一个这样的例子,让我知道。

希望这会有所帮助。

+4

下面是绑定的一种快速示例,其中div通过'style'绑定绑定,用于设置对象的值并使用'event'绑定通过拖动或调整大小来跟踪更新。 http://jsfiddle.net/rniemeyer/a6Gjs/ – 2011-04-10 19:27:54

+0

你的答案是一个敲出公园的答案。我真的很感激。 – 2011-04-11 02:38:14

+0

大声笑没有双关语意。 – 2011-04-11 03:23:21

相关问题