-
Notifications
You must be signed in to change notification settings - Fork 17
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
New: Added toggleClass to AdaptModel and ItemModel (fixes #593)
* New: Added toggleClass to AdaptModel and ItemModel * Updated comment
- Loading branch information
1 parent
d8d6b24
commit a500a54
Showing
3 changed files
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,32 @@ | ||
/** | ||
* Toggle a className in the _classes attribute of any Backbone.Model | ||
* @param model {Backbone.Model} Model with a _classes attribute to modify | ||
* @param className {string} Name or names of class to add/remove to _classes attribute, space separated list | ||
* @param hasClass {boolean|null|undefined} true to add a class, false to remove, null or undefined to toggle | ||
*/ | ||
export function toggleModelClass(model, className, hasClass) { | ||
// split the string of classes into an array of classNames | ||
const currentClassNames = (model.get('_classes') || '').split(' ').filter(Boolean); | ||
// capture all existing classes as a unique list | ||
const classesObject = currentClassNames.reduce((classesObject, className) => ({ ...classesObject, [className]: true }), {}); | ||
// update the list according to arguments | ||
const shouldToggleExisting = (hasClass === null || hasClass === undefined); | ||
// allow multiple classes to be added and removed together | ||
className | ||
.split(' ') | ||
.filter(Boolean) | ||
.forEach(className => { | ||
// toggle class | ||
classesObject[className] = shouldToggleExisting | ||
? !classesObject[className] | ||
: Boolean(hasClass); | ||
}); | ||
// flatten back into a string of classes | ||
const outputClasses = Object | ||
.entries(classesObject) | ||
.filter(([, hasClass]) => hasClass) | ||
.map(([className]) => className) | ||
.join(' '); | ||
// update the model | ||
model.set('_classes', outputClasses); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters