补充上个监控数组ko.observableArray()
ko常用的绑定:text绑定,样式绑定,数据数组绑定、 visible 绑定、属性绑定
1.visible绑定
<div data-bind="visible: shouldShowMessage">
你可以看见我,在js里面设置
</div>
<script>
var viewModel = {
shouldShowMessage: ko.observable(true) // Message initially visible
};
viewModel.shouldShowMessage(false); // ... now it's hidden
viewModel.shouldShowMessage(false);
ko.applyBindings(viewModel);
</script>
data-bind="visible: myValues().length > 0"绑定的时候也可以用是一个数组的长度判断
2.text绑定
Today's message is: <span data-bind="text: myMessage"></span>
<script>
var viewModel = {
myMessage: ko.observable() // Initially blank
};
viewModel.myMessage("Hello, world!"); // Text appears
ko.applyBindings(viewModel);
使用函数对text进行绑定
var viewModel = {
price: ko.observable(24.95)
};
viewModel.priceRating = ko.dependentObservable(function () {
returnthis.price() >50?"expensive" : "affordable";
}, viewModel);
或者直接使用data-bind绑定三目运算
data-bind="text: price() > 50 ? 'expensive' : 'affordable'"
3.css绑定
var viewModel = {
currentProfit: ko.observable(150000)
// Positive value, so initially we don't apply the "profitWarning" class
};
viewModel.currentProfit(-230);
4.style绑定
<div data-bind="style: { color: currentProfit() < 0 ? 'red' : 'black' }">
Profit Information
</div>
<script type="text/javascript">
var viewModel = {
currentProfit: ko.observable(150000) // Positive value, so initially black
};
viewModel.currentProfit(-50); // Causes the DIV's contents to go red
</script>
5.attr绑定
<a data-bind="attr: { href: url, title: details }">
Report
</a>
<script type="text/javascript">
var viewModel = {
url: ko.observable("year-end.html"),
details: ko.observable("Report including final year-end statistics")
};
</script>
6.click绑定
<div>
You've clicked <span data-bind="text: numberOfClicks"></span> times
<button data-bind="click: incrementClickCounter">Click me</button>
</div>
<script>
var viewModel = {
numberOfClicks: ko.observable(0),
incrementClickCounter: function () {
var previousCount =this.numberOfClicks();
this.numberOfClicks(previousCount +1);
}
};//声明的函数不一定是在viewmodel中,也可以直接写成一个普通函数
ko.applyBindings(viewModel);
以匿名函数的方式传参
<div>
You've clicked <span data-bind="text: numberOfClicks"></span> times
<button data-bind="click: function() { viewModel.myFunction('param1', 'param2') }">Click me</button>
</div>
<script>
var viewModel = {
numberOfClicks: ko.observable(0),
myFunction:function(q,w){
console.log(q)
console.log(w)
}
};
ko.applyBindings(viewModel);
默认情况下,Knockout会阻止冒泡,防止默认的事件继续执行。例如,如果你点击一个a连接,在执行完自定义事件时它不会连接到href地址。这特别有用是因为你的自定义事件主要就是操作你的view model,而不是连接到另外一个页面。默认情况下,Knockout允许click事件继续在更高一层的事件句柄上冒泡执行。例如,如果你的元素和父元素都绑定了click事件,那当你点击该元素的时候两个事件都会触发的。如果需要,你可以通过额外的绑定clickBubble来禁止冒泡
<button data-bind="click: myButtonHandler, clickBubble: false">
Click me
</button>
7event绑定
大部分情况下是键盘事件、鼠标事件
<div>
<div data-bind="event: { mouseover: enableDetails, mouseout: disableDetails }">
Mouse over me
</div>
<div data-bind="visible: detailsEnabled">
Details
</div>
</div>
<script type="text/javascript">
var viewModel = {
detailsEnabled: ko.observable(false),
enableDetails: function () {
this.detailsEnabled(true);
},
disableDetails: function () {
this.detailsEnabled(false);
}
};
</script>
访问源对象
<div data-bind="event: { mouseover: myFunction }">
Mouse over me
</div>
//通过event获取
<script type="text/javascript">
var viewModel = {
myFunction: function (event) {
if (event.shiftKey) {
//do something different when user has shift key down
} else {
//do normal action
}
}
};
</script>
注:如果允许执行默认事件执行,只要在自定义事件里,对event返回为true
8.enable绑定
enable绑定使DOM元素只有在参数值为 true的时候才enabled。在form表单元素input,select,和textarea上非常有用。
<p>
<input type='checkbox' data-bind="checked: hasCellphone"/>
I have a cellphone
</p>
<p>
Your cellphone number:
<input type='text' data-bind="value: cellphoneNumber, enable: hasCellphone"/>
<button data-bind="click:indexme">点我</button>
</p>
<script>
var viewModel = {
hasCellphone: ko.observable(false),
cellphoneNumber: ""
};
function indexme(){
console.log(viewModel.cellphoneNumber)
}
ko.applyBindings(viewModel);
disable绑定使DOM元素只有在参数值为 true的时候才disabled。在form表单元素input,select,和textarea上非常有用。
disable绑定和enable绑定正好相反,详情请参考enable绑定。
9.value绑定
<p>Login name: <input data-bind="value: userName"/></p>
<p>Password: <input type="password" data-bind="value: userPassword"/></p>
<script>
var viewModel = {
userName: ko.observable(""), // Initially blank
userPassword: ko.observable("abc"), // Prepopulate
};
ko.applyBindings(viewModel);
特殊参数 valueUpdate
- 默认“change”事件,自动更新
- ‘keyup’
- 'keypress'
- 'afterkeydown'
例子
<p>Your value: <input data-bind="value: someValue, valueUpdate: 'afterkeydown'"/></p>
<p>You have typed: <span data-bind="text: someValue"></span></p> <!-- updates in real-time -->
<script type="text/javascript">
var viewModel = {
someValue: ko.observable("edit me")
};
</script>
10 check绑定
注:对text box,drop-down list和所有non-checkable的form表单控件,用value绑定来读取和写入是该元素的值,而不是checked绑定
<p>Send me spam: <input type="checkbox" data-bind="checked: wantsSpam"/></p>
<script type="text/javascript">
var viewModel = {
wantsSpam: ko.observable(true) // Initially checked
};
// ... then later ...
viewModel.wantsSpam(false); // The checkbox becomes unchecked
</script>
绑定数组
<p>Send me spam: <input type="checkbox" data-bind="checked: wantsSpam"/></p>
<div data-bind="visible: wantsSpam">
Preferred flavors of spam:
<div><input type="checkbox" value="cherry" data-bind="checked: spamFlavors"/> Cherry</div>
<div><input type="checkbox" value="almond" data-bind="checked: spamFlavors"/> Almond</div>
<div><input type="checkbox" value="msg" data-bind="checked: spamFlavors"/> Monosodium Glutamate</div>
</div>
<script>
var viewModel = {
wantsSpam: ko.observable(true),
spamFlavors: ko.observableArray(["cherry", "almond"]) // Initially checks the Cherry and Almond checkboxes
};
// ... then later ...
viewModel.spamFlavors.push("msg");
ko.applyBindings(viewModel);
radio绑定
<p>Send me spam: <input type="checkbox" data-bind="checked: wantsSpam"/></p>
<div data-bind="visible: wantsSpam">
Preferred flavor of spam:
<div><input type="radio" name="flavorGroup" value="cherry" data-bind="checked: spamFlavor"/> Cherry</div>
<div><input type="radio" name="flavorGroup" value="almond" data-bind="checked: spamFlavor"/> Almond</div>
<div><input type="radio" name="flavorGroup" value="msg" data-bind="checked: spamFlavor"/> Monosodium Glutamate</div>
</div>
<script>
var viewModel = {
wantsSpam: ko.observable(true),
spamFlavor: ko.observable("almond") // Initially selects only the Almond radio button
};
// ... then later ...
viewModel.spamFlavor("msg");
ko.applyBindings(viewModel);
11.options绑定
例子1
<p>Destination country: <select data-bind="options: availableCountries"></select></p>
<script type="text/javascript">
var viewModel = {
availableCountries: ko.observableArray(['France', 'Germany', 'Spain']) // These are the initial options
};
// ... then later ...
viewModel.availableCountries.push('China'); // Adds another option
</script>
例子2
<p>Choose some countries you'd like to visit: <select data-bind="options: availableCountries" size="5" multiple="true"></select></p>
<script type="text/javascript">
var viewModel = {
availableCountries: ko.observableArray(['France', 'Germany', 'Spain'])
};
</script>
例子3
<p>
Your country:
<select data-bind="options: availableCountries,
optionsText: 'countryName', value: selectedCountry, optionsCaption: 'Choose...'"></select>
</p>
<div data-bind="visible: selectedCountry"> <!-- Appears when you select something -->
You have chosen a country with population
<span data-bind="text: selectedCountry() ? selectedCountry().countryPopulation : 'unknown'"></span>.
</div>
<script type="text/javascript">
// Constructor for an object with two properties
var country =function (name, population) {
this.countryName = name;
this.countryPopulation = population;
};
var viewModel = {
availableCountries: ko.observableArray([
new country("UK", 65000000),
new country("USA", 320000000),
new country("Sweden", 29000000)
]),
selectedCountry: ko.observable() // Nothing selected by default
};
</script>
例子4
<p>
Your country:
<select data-bind="options: availableCountries,
optionsText: 'countryName', value: selectedCountry, optionsCaption: 'Choose...'"></select>
</p>
<div data-bind="visible: selectedCountry"> <!-- Appears when you select something -->
You have chosen a country with population
<span data-bind="text: selectedCountry() ? selectedCountry().countryPopulation : 'unknown'"></span>.
</div>
<script>
var country =function (name, population) {
this.countryName = name;
this.countryPopulation = population;
};
var viewModel = {
availableCountries: ko.observableArray([
new country("UK", 65000000),
new country("USA", 320000000),
new country("Sweden", 29000000)
]),
//selectedCountry是选择下拉框的value值
selectedCountry: ko.observable() // Nothing selected by default
};
ko.applyBindings(viewModel);
参数
主参数
该参数是一个数组(或者observable数组)。对每个item,KO都会将它作为一个<option> 添加到<select>里,之前的options都将被删除。
如果参数是一个string数组,那你不需要再声明任何其它参数。<select>元素会将每个string显示为一个option。不过,如果你让用户选择的是一个JavaScript对象数组(不仅仅是string),那就需要设置optionsText和optionsValue这两个参数了。
如果参数是监控属性observable的,那元素的options项将根据参数值的变化而更新,如果不是,那元素的value值将只设置一次并且以后不在更新。
其它参数
optionsCaption
有时候,默认情况下不想选择任何option项。但是single-select drop-down列表由于每次都要默认选择以项目,怎么避免这个问题呢?常用的方案是加一个“请选择的”或者“Select an item”的提示语,或者其它类似的,然后让这个项作为默认选项。
我们使用optionsCaption参数就能很容易实现,它的值是字符串型,作为默认项显示。例如:
<select data-bind='options: myOptions, optionsCaption: "Select an item...", value: myChosenValue'></select>
KO会在所有选项上加上这一个项,并且设置value值为undefined。所以,如果myChosenValue被设置为undefined(默认是observable的),那么上述的第一个项就会被选中。
optionsText
上面的例3展示的绑定JavaScript对象到option上 – 不仅仅是字符串。这时候你需要设置这个对象的那个属性作为drop-down列表或multi-select列表的text来显示。例如,例3中使用的是设置额外的参数optionsText将对象的属性名countryName作为显示的文本。
如果不想仅仅显示对象的属性值作为每个item项的text值,那你可以设置optionsText 为JavaScript 函数,然后再函数里通过自己的逻辑返回相应的值(该函数参数为item项本身)。例4展示的就是返回item的2个属性值合并的结果。
optionsValue
和optionsText类似, 你也可以通过额外参数optionsValue来声明对象的那个属性值作为该<option>的value值。
经典场景:如在更新options的时候想保留原来的已经选择的项。例如,当你重复多次调用Ajax获取car列表的时候,你要确保已经选择的某个car一直都是被选择上,那你就需要设置optionsValue为“carId”或者其它的unique标示符,否则的话KO找不知道之前选择的car是新options里的哪一项。
selectedOptions
对于multi-select列表,你可以用selectedOptions读取和设置多个选择项。技术上看它是一个单独的绑定,有自己的文档,请参考: selectedOptions绑定。
注:已经被选择的项会再options改变的时候保留
当使用options绑定<select>元素的时候,如果options改变,KO将尽可能第保留之前已经被选择的项不变(除非是你事先手工删除一个或多个已经选择的项)。这是因为options 绑定尝试依赖value值的绑定(single-select列表)和selectedOptions绑定(multi-select列表)。