Skip to content

Commit

Permalink
"attr" binding now removes attributes if the bound value is strictly …
Browse files Browse the repository at this point in the history
…false (thanks to Greenlaw for providing this use case)
  • Loading branch information
SteveSanderson committed Feb 8, 2011
1 parent c416c1f commit 775ee38
Show file tree
Hide file tree
Showing 4 changed files with 11 additions and 5 deletions.
5 changes: 4 additions & 1 deletion build/output/knockout-latest.debug.js
Original file line number Diff line number Diff line change
Expand Up @@ -1467,7 +1467,10 @@ ko.bindingHandlers['attr'] = {
for (var attrName in value) {
if (typeof attrName == "string") {
var attrValue = ko.utils.unwrapObservable(value[attrName]);
if (attrValue === undefined)

// To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
// when someProp===false (because that's how to mark an element as not checked, not disabled, etc.)
if (attrValue === false)
element.removeAttribute(attrName);
else
element.setAttribute(attrName, attrValue.toString());
Expand Down
2 changes: 1 addition & 1 deletion build/output/knockout-latest.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions spec/defaultBindingsBehaviors.js
Original file line number Diff line number Diff line change
Expand Up @@ -694,7 +694,7 @@ describe('Binding: Attr', {
value_of(testNode.childNodes[0].getAttribute("second-attribute")).should_be("true");
},

'Should respond to changes in an observable value, removing the attribute if the value is undefined': function() {
'Should respond to changes in an observable value, removing the attribute if the value is strictly false': function() {
var model = { myprop : ko.observable("initial value") };
testNode.innerHTML = "<div data-bind='attr: { someAttrib: myprop }'></div>";
ko.applyBindings(model, testNode);
Expand All @@ -705,7 +705,7 @@ describe('Binding: Attr', {
value_of(testNode.childNodes[0].getAttribute("someAttrib")).should_be("new value");

// Set to undefined; see the attribute vanish
model.myprop(undefined);
model.myprop(false);
value_of(testNode.childNodes[0].getAttribute("someAttrib")).should_be(null);
}
});
5 changes: 4 additions & 1 deletion src/binding/defaultBindings.js
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,10 @@ ko.bindingHandlers['attr'] = {
for (var attrName in value) {
if (typeof attrName == "string") {
var attrValue = ko.utils.unwrapObservable(value[attrName]);
if (attrValue === undefined)

// To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
// when someProp===false (because that's how to mark an element as not checked, not disabled, etc.)
if (attrValue === false)
element.removeAttribute(attrName);
else
element.setAttribute(attrName, attrValue.toString());
Expand Down

0 comments on commit 775ee38

Please sign in to comment.