Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <div class="container">
  <h1>Dwarves Assemble!!!!!<br/>
  <small> an example with <strong>Knockout.js</strong> Observable Arrays brought to you by <a href="http://www.barbarianmeetscoding.com">barbarian meets coding</a></small></h1>
 
  <div class="row">
    <div class="col-md-8 col-md-offset-2">
            <img src="http://img-fan.theonering.net/~rolozo/images/wyatt/unexpected.jpg" width="300">
      <blockquote>
        <p>
  In a hole in the ground there lived a hobbit. Not a nasty, dirty, wet hole, filled with the ends of worms and an oozy smell, nor yet a dry, bare, sandy hole with nothing in it to sit down on or to eat: it was a hobbit-hole, and that means comfort.
        </p>
      </blockquote>
    </div>
  </div>
  

  <h2>Gather Your Party and Venture Forth!!!</h2>
  <h3>Party</h3>
  
  <div class="row party" data-bind="foreach: members">
    <div class="partymember">
        <img data-bind="attr: {src: image}">
        <p data-bind="text: name"></p>
        <button class="btn btn-danger" data-bind="click: $parent.remove">remove</button>
    </div>
  </div>  
  
  <h3>Select More Heroes</h3>
  <div class="row party" data-bind="foreach: selectableMembers">
    <div class="partymember">
        <img data-bind="attr: {src: image}">
        <p data-bind="text: name"></p>
        <button class="btn btn-primary" data-bind="click: $parent.add">add</button>
    </div>
  </div>  

  <h2>...And Some Examples of Observable Array Operations</h2>
  
  <h3>Basic Array Operations</h3>
  <div class="row">
    <p>
    <div class="btn-group">
      <button type="button" class="btn btn-default" data-bind="click: pushDwarf">Push</button>
      <button type="button" class="btn btn-default" data-bind="click: popDwarf">Pop</button>
    </div>
    <div class="btn-group">
      <button type="button" class="btn btn-default" data-bind="click: unshiftDwarf">Unshift</button>
      <button type="button" class="btn btn-default" data-bind="click: shiftDwarf">Shift</button>
    </div>
    <button type="button" class="btn btn-default" data-bind="click: reverseDwarves">Reverse</button>
    <button type="button" class="btn btn-default" data-bind="click: sortDwarves">Sort</button>
    <div class="btn-group">
      <button type="button" class="btn btn-default" data-bind="click: spliceDwarves">Splice</button>
      <button type="button" class="btn btn-default" data-bind="click: sliceDwarves">Slice</button>
    </div>  
  </p>
</div>

  <p><span class="glyphicon glyphicon-asterisk"></span>Notice how <strong>slice</strong> does not trigger an update in the observable array and thus no message is shown when you click on it. That makes perfectly sense since slice does not modify the original array. It just makes a shallow copy of its contents and returns it.</p>

  <h3>Additional Sugary Operations</h3>
  <div class="row">
    <p>
    <div class="btn-group">
      <button type="button" class="btn btn-default" data-bind="click: removeBilbo">Remove Bilbo</button>
      <button type="button" class="btn btn-default" data-bind="click: removeAllDwarves">Remove all dwarf warriors</button>
      <button type="button" class="btn btn-default" data-bind="click: removeAllDwarvesThatAreWarriors">Remove all warriors</button>
      <button type="button" class="btn btn-default" data-bind="click: removeAllFromTheCompany">Remove all</button>
    </div>
  </p>
</div>



</div>

    <div data-bind="alert: members" class="dasToast">
      <div class="alert alert-warning fade in">
        <p data-bind="with: operationInfo">
          <strong data-bind="text: operation"></strong>
          <span data-bind="text: description"></span>
        </p>
      </div>
    </div>  

<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery.js"></script>
<script   src="https://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
              
            
!

CSS

              
                img {
  display: block;
  margin: auto;
}

.dasToast{
  display: block;
  position: absolute;
  bottom: 10px;
  right: 10px;
}

.party {
  display: flex;
}

.partymember{
  width: 150px;
  margin: 10px;
}

.partymember img{
  width: 100%;
  border: 2px #777 solid;
}
              
            
!

JS

              
                // custom binding to wrap alert
ko.bindingHandlers['alert'] = {
  init: function(element, valueAccessor){
    $(element).hide();
  },
  update: function(element, valueAccessor){
    //return;
    var helperDiv,
        showAlert = ko.utils.unwrapObservable(valueAccessor());
    if (showAlert){
      $(element).fadeIn('slow');
      setTimeout(function(){
        $(element).fadeOut('slow');
      }, 1500);
    }
  }
};

// Model
var bilbo =   {
    name: "Bilbo Baggins",
    race: "Hobbit",
    classType: "Thief",
    image: "http://www.barbarianmeetscoding.com/images/ko-gandalf-2.png"
  },
    gandalf = {
    name: "Gandalf, the Grey",
    race: "Istari",
    classType: "Wizard",
    image: "http://www.barbarianmeetscoding.com/images/ko-gandalf-2.png"
  };


var bilboGandalfAndTheDwarves = [
  bilbo,
  gandalf,
  {
    name: "Thorin Oakenshield",
    race: "Dwarf",
    classType: "King",
        image: "http://www.barbarianmeetscoding.com/images/ko-gandalf-2.png"
  },
  {
    name: "Bombur",
    race: "Dwarf",
    classType: "Warrior",
        image: "http://www.barbarianmeetscoding.com/images/ko-gandalf-2.png"
  }];

var otherHeroes = [
  {
    name: "Balin",
    race: "Dwarf",
    classType: "Warrior",
        image: "http://www.barbarianmeetscoding.com/images/ko-gandalf-2.png"
  },
    {
    name: "Bofur",
    race: "Dwarf",
    classType: "Warrior",
        image: "http://www.barbarianmeetscoding.com/images/ko-gandalf-2.png"
  },
    {
    name: "Dwalin",
    race: "Dwarf",
    classType: "Warrior",
        image: "http://www.barbarianmeetscoding.com/images/ko-gandalf-2.png"
  }
];

// ViewModel
var Company = function(members, others){
  var self = this;
  self.members = ko.observableArray(members);
  self.selectableMembers = ko.observableArray(others);
  self.operationInfo = ko.observable({
    operation: "Yey!", 
    description: "To the Lonely Mountain! FTW!"
  });
  
  // Note how this method is part of the constructor function
  // and not the prototype.
  //
  // That is because when we call this method from a different
  // data binding context (i.e. every single item within members
  // as this method is bound to the remove button), 
  // that context becomes the owner
  // of the method (that is, it becomes this)
  //
  // Because of that, in order to ensure that
  // the method has access to members
  // we add it inside the constructor function so it
  // can create a closure around self
  self.remove = function(partyMember){
    var removedMembers = self.members.remove(partyMember);
    removedMembers.forEach(function(m){self.selectableMembers.push(m);});
    self.operationInfo({
      operation: "remove",
      description: "Removed " + partyMember.name + " from the company. Bye Hobbit!"
    });
  };
  
  self.add = function(newPartyMember){
    self.selectableMembers.remove(newPartyMember);
    self.members.push(newPartyMember);
     self.operationInfo({
      operation: "add",
      description: "Added " + newPartyMember.name + " to the company. Adventure!!!"
    });
  };
}

Company.prototype.pushDwarf = function(){
  var self = this,
      newDwarf = {
      name: "Biffur",
      race: "Dwarf",
      classType: "Warrior",
      image: "http://www.barbarianmeetscoding.com/images/ko-gandalf-2.png"
  };
  self.members.push(newDwarf);
  self.operationInfo({
    operation: "push",
    description: "Added one dwarf to the end of the array. Welcome to the company of Thorin OakenShield!"
  });
};

Company.prototype.popDwarf = function(){
  var self = this;
  self.members.pop();
  self.operationInfo({
    operation: "pop",
    description: "Removed one dwarf at the end of the array. Bye! Bye!"
  });
};

Company.prototype.unshiftDwarf = function(){
  var self = this,
      newDwarf = {
    name: "Biffur",
    race: "Dwarf",
    classType: "Warrior",
    image: "http://www.barbarianmeetscoding.com/images/ko-gandalf-2.png"
  };
  self.members.unshift(newDwarf);
  self.operationInfo({
    operation: "unshift",
    description: "Added one dwarf at the beginning of the array. Mead for All!!"});
};

Company.prototype.shiftDwarf = function(){
  var self = this;
  self.members.shift();
  self.operationInfo({
    operation: "shift",
    description: "Removed one dwarf at the beginning of the array. Ahhh!!"});
};

Company.prototype.reverseDwarves = function(){
  var self = this;
  self.members.reverse();
  self.operationInfo({
    operation: "reverse",
    description: "Reverse the dwarves in the array. Wihoooo!!"});
};

Company.prototype.sortDwarves = function(){
  var self = this;
  self.members.sort(function(aDwarf, anotherDwarf) { 
    if (aDwarf.name == anotherDwarf.name)
      return 0;
    return aDwarf.name < anotherDwarf.name ? -1 : 1;
  });
  self.operationInfo({
    operation: "sort",
    description: "Sort the dwarves alphabetically. A, B, C...!!"});
};

Company.prototype.spliceDwarves = function(){
  var self = this;
  self.members.splice(1,1);
  self.operationInfo({
    operation: "splice",
    description: "Removing the second dwarf. You can splice anything, anywhere!"});
};


Company.prototype.sliceDwarves = function(){
  var self = this,
      slicedDwarves = self.members.slice(1,2);
  self.operationInfo({
    operation: "slice",
    description: "Creating an new array with the second dwarf:"  + slicedDwarves.toString() + ". You can splice anything, anywhere!"});
};
  
Company.prototype.removeBilbo = function(){
  var self = this,
      removedAdventureres = self.members.remove(bilbo);
  self.operationInfo({
    operation: "remove",
    description: "Removed Bilbo from the company. Bye Hobbit!"
  });
};

Company.prototype.removeAllDwarves = function(){
  var self = this,
      dwarves = self.members.remove(function(member){
        return member.race === 'Dwarf';
      });
  self.operationInfo({
    operation: "remove",
    description: "Remove accepts a predicate as an argument which allows you to remove whichever item satisfies it from the observable array"
  });
};


Company.prototype.removeAllDwarvesThatAreWarriors = function(){
    var self = this,
      dwarves = self.members.remove(function(member){
        return member.race === 'Dwarf' && member.classType === 'Warrior';
      });
  self.operationInfo({
    operation: "remove",
    description: "Remove accepts a predicate as an argument which allows you to remove whichever item satisfies it from the observable array"
  });
};


Company.prototype.removeAllFromTheCompany = function(){
   var self = this,
       allMembers = self.members.removeAll();
  self.operationInfo({
    operation: "removeAll",
    description: "Remove all allows you to clear an observable array completely, or remove a collection of items."
  });
};


ko.applyBindings(new Company(bilboGandalfAndTheDwarves, otherHeroes));

// TODO:
// 1 - add own image from bmc
// 2 - continue implementing ko observable methods
              
            
!
999px

Console