[英]Accessing property of observable object inside observable array - knockout.js
[英]Knockout.js - Arrays/Object Literals and accessing a property for an audio path
因此,我花了一些時間來學習淘汰賽,到目前為止,我很開心。 我一直在尋找使用Knockout的好用例,我想我已經在吉他調音器“單頁應用程序”中找到了一個。
我在這里:
這是我的HTML和底層js模型
<!-- Scripts -->
<script src="js/jquery-2.1.1.min.js"></script>
<script src="js/knockout-3.1.0.min.js"></script>
<script src="js/driver.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- Pull the string data from the guitar object and populate it here. -->
<ul data-bind="foreach: guitars" class="guitars">
<span>This is a <span data-bind="text: notes().length"></span> stringed guitar</span>
<button data-bind="click: addNote">Addnote</button>
<li>
<ul data-bind="foreach: notes" class="audio-triggers">
<li><a data-bind="text: $data" href="#"></a></li>
</ul>
</li>
</ul>
...
</body>
JS:$(document).ready(function(){
// Guitar Class that has its own note adder.
var Guitar = function(strings, notes) {
this.strings = strings;
this.notes = ko.observableArray(notes);
this.audioPaths = retrieveAudio(notes);
this.addNote = function() {
this.notes.push("f");
this.strings = this.strings++;
}.bind(this);
}
// The view model is an abstract description of the state of the UI, but without any knowledge of the UI technology (HTML)
var viewModel = {
guitars: [
new Guitar(3, ["e", "a", "d"]),
new Guitar(6, ["e", "a", "d", "a", "d", "g"])
]
};
ko.applyBindings(viewModel);
});
// Functions
function retrieveAudio(notes) {
var paths = {}
// For each note, access the audio path
$.each(notes, function(index, val){
paths.note = val;
paths.note.path = 'audio/1.mp3'
});
return paths;
}
從本質上講,我希望能夠使用注釋數組,並使用注釋的名稱作為文件的名稱來確定音頻路徑,但是我有點卡住了,因為我不確定是否存在“刪除”方式。
我的想法是編寫一個外部函數,該函數將根據傳入的注釋填充對象以返回音頻路徑,但是同樣,我仍然不確定如何在相應的HTML中訪問它。 因為到目前為止,它只是在不是對象的元素上使用數據綁定。
我想我的問題是:
data-bind: foreach
嗎? 我假設我將以與我訪問notes數組本身的方式相似的方式訪問note路徑,並使用foreach數據綁定。 我想我的最后一個問題是,如何訪問對象文字中的嵌套屬性(假設我可以進行data-bind: foreach
通過它進行data-bind: foreach
?)。
我感謝任何提示/提示/幫助! :)
我會考慮將數組中的注釋轉換為具有自己的path屬性的單個對象。 如果可以計算文件的路徑,則可以使用ko.computed來基於實體注釋值來計算路徑。
所以你最終會得到類似
// Guitar Class that has its own note adder.
var Guitar = function (strings, notes) {
var self = this;
self.strings = strings;
self.notes = ko.observableArray($.map(notes, function (item, index) {
return new Note(item);
}));
self.addNote = function () {
self.notes.push(new Note());
self.strings = this.strings++;
}.bind(self);
};
var Note = function (noteName) {
var self = this;
self.noteName = ko.observable(noteName || 'f');
self.audioPath = ko.computed(function () {
return 'audio/' + self.noteName() + '.mp3';
});
};
// The view model is an abstract description of the state of the UI, but without any knowledge of the UI technology (HTML)
var viewModel = {
guitars: [
new Guitar(3, ["e", "a", "d"]),
new Guitar(6, ["e", "a", "d", "a", "d", "g"])]
};
ko.applyBindings(viewModel);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.