logo
down
shadow

Knockout JS: adding forms in foreach bindings


Knockout JS: adding forms in foreach bindings

Content Index :

Knockout JS: adding forms in foreach bindings
Tag : javascript , By : Ambarish Singh
Date : November 28 2020, 04:01 AM

hope this fix your issue
Not sure if you are writing delete function on comment level or its list level but if are binding the function use $parent to get out of foreach context.
function viewModel() {
  var self = this;
  
  self.comments = ko.observableArray([]);
  self.isDataLoaded = ko.observable(false);
  
  self.loadData = function(){
    setTimeout(function(){ 
      self.comments.push({username:"A", sameUser:true, commentID:1, text:"This is comment from A"});
      self.comments.push({username:"B", sameUser:true, commentID:2, text:"This is comment from B"});
      self.comments.push({username:"C", sameUser:false, commentID:3, text:"This is comment from C"});
      self.comments.push({username:"D", sameUser:true, commentID:4, text:"This is comment from D"});
      self.isDataLoaded(true);
    }, 2000);
  }
  self.deleteComment = function(data){
    self.comments.remove(data);
  }
}

var vm = new viewModel();
vm.loadData();
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul data-bind="foreach: comments">
    <li>
        <span data-bind="text: username"></span>
        <ul>
            <li data-bind="text: text"></li>
            <!--<li data-bind="text: timestamp"></li> -->
            <form data-bind="if: sameUser" method="post">
                <input data-bind="attr: {id: commentID}, click: $parent.deleteComment" type="submit"        value="Delete comment">
            </form>
        </ul>
    </li>
</ul>

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

Knockout JS - If bindings inside foreach


Tag : javascript , By : Ben
Date : March 29 2020, 07:55 AM
I wish did fix the issue. For an expression such as if: mediatype === '2' you'd need to use brackets i.e. if: mediatype() === '2'

Knockout bindings breaking in foreach binding


Tag : javascript , By : cheese_doodle
Date : March 29 2020, 07:55 AM
wish helps you I would advise to not mix fixed content with templated content, possibly using virtual elements, as shown here below:
<ul>
    <li data-bind="text: PermittingCAAActive"></li>
    <!-- ko template: {name: 'tablsUlTemplate', foreach: Operators} -->
    <!-- /ko -->
</ul>

<script type="text/html" id="tablsUlTemplate">
    <li><a data-bind="attr: { href: NameHash }" data-toggle="tab"><span data-bind="text: Name"></span></a></li>
</script>

Knockout form bindings foreach


Tag : knockout.js , By : msg
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , If you give each task a selectedOption property and a notes property, their values will be bound to their parent task.
Have a look at this (fiddle: http://jsfiddle.net/jRyS7/2/):
var Note = function(note){
    var self = this;
    self.note = ko.observable(note);
}

var Task = function(title, notes){
    var self = this;
    self.title = ko.observable(title);
    self.selectedOption = ko.observable();
    self.notes = ko.observableArray();
    for (var i = 0; i< notes.length; i++){ 
        self.notes.push(new Note(notes[i]));
    }   
    self.addRow = function(){
        self.notes.push(new Note("newNote"));
    }
}

var VM = function(){
    var self = this;

    self.option = [
        "option1",
        "option2"
        ]

    self.tasks = ko.observableArray([
        new Task("task1", ["note1.1", "note1.2"]),
        new Task("task2", ["note2.1", "note2.2"]),
        new Task("task3", ["note3.1", "note3.2"])
    ])

    self.addTask = function(){
        self.tasks.push(new Task("newTask", ["newNote1", "newNote2"]));
    }

}

        ko.applyBindings(new VM());

Knockout.JS custom bindings. Updating foreach


Tag : javascript , By : Hadley
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , I'm trying to parse the object, which come from JSON file. It looks like this: , I found the solution. Just use the built-in foreach update method :
    ko.bindingHandlers.getLocalizedScreenshot = 
{
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext)
    {
        var languageIndex = self.displayLanguages.indexOf(self.currentLanguage());
        var array = ko.observableArray(languageIndex>valueAccessor().length-1? valueAccessor()[0] : valueAccessor()[languageIndex] , allBindingsAccessor);            
        return ko.bindingHandlers.foreach.init(element, array, allBindingsAccessor, viewModel, bindingContext);
    },
    update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext)
    {
        var languageIndex = self.displayLanguages.indexOf(self.currentLanguage());
        var array = ko.observableArray(languageIndex>valueAccessor().length-1? valueAccessor()[0] : valueAccessor()[languageIndex] , allBindingsAccessor);
        ko.bindingHandlers.foreach.update(element, array , allBindingsAccessor, viewModel, bindingContext);
        return { controlsDescendantBindings: true };       
    }
};

knockout - how to use option and foreach bindings together


Tag : javascript , By : MrSparky
Date : March 29 2020, 07:55 AM
I hope this helps you . simplest way is to use ko.mapping plugin
or you can manually make each array object properties to observable.
var dataCameFromServer = { foo: "1", bar: "sag", results: [{ slectedBoxID: null, selectBoxOptions: [{ id: 1, name: "mosi" }, { id: 2, name: "azi" }, { id: 3, name: "mom" }, { id: 4, name: "dad" } ] }, { slectedBoxID: 2, selectBoxOptions: [{ id: 1, name: "tehran" }, { id: 2, name: "masal" }, { id: 3, name: "gilan" }, { id: 4, name: "rasht" } ] }, { slectedBoxID: 1, selectBoxOptions: [{ id: 1, name: "adidas" }, { id: 2, name: "nike" }, { id: 3, name: "rebook" }, { id: 4, name: "puma" } ] } ] };

function selectViewModel() {
  var self = this;
  // using ko.mapping 
  this.data = ko.mapping.fromJS(dataCameFromServer);
  this.sbValue = self.data.results().map(v => v.slectedBoxID);
}

ko.applyBindings(new selectViewModel(), $("#wrapper")[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>
<div id="wrapepr">
  <!-- ko with: data -->
  <!-- ko foreach: results -->
  <select data-bind="options:selectBoxOptions,optionsText: 'name',optionsValue: 'id',value: slectedBoxID,optionsCaption: 'Choose...'"></select>
  <!-- /ko -->
  <!-- /ko -->
</div>
<pre data-bind="text: ko.toJSON(sbValue, null, 2)"></pre>
Related Posts Related QUESTIONS :
  • How to surround selected text inside textarea with <em> on key combination CTRL+i?
  • Your configured registry does not support audit requests ~ On npm audit
  • What's the Angular equivalent of Vue <slot/>?
  • Iconify icon not updating when "data-icon" set with setAttribute()
  • Javascript newbie stuck with XMLHttpRequest return data
  • How to add obj to to state in my example Redux React
  • Loading "grunt-karma.js" tasks...ERROR >> SyntaxError: Unexpected identifier
  • Why do I get log is not defined
  • get the multiple index of the same string
  • How can I iterate over an Array object by using For IN or FOR OF
  • Launch local executable from web browser
  • How to prepare array of json objects to d3 hierarchical tree structure
  • VueJS - event emitted - show HTML before other calculations
  • Export SASS/SCSS variables to Javascript without exporting them to CSS
  • How to attach an event handler only once continuously
  • How to make button open a link in new tab in JavaScript?
  • Find range from the javascript object
  • How can I use my jQuery code as JavaScript?
  • How to show 5 images in a 2 row slider with bxslider
  • How to convert stream into variables in typescript
  • Three.js custom shader error on Chrome GL_INVALID_OPERATION: Active draw buffers with missing fragment shader outputs
  • My JavaScript doesn't work. How can I solve this problem?
  • Why is this async function is running synchronously?
  • Get updated variable from within react hook before return
  • I want to show all image preview but whenever I upload a new one the old one is gone
  • Would I be able to give access to specific electron APIs safely?
  • Why several clicks fire for each instance of a Class?
  • cant grab value from div using attr()
  • Make web service not accessible by browser?
  • Select DOM elements within template
  • How to customize angular ui-grid row background color?
  • Binding data in two respective $scope in AngularJS, how?
  • react put some props after import class
  • Variable is distributed among same components
  • switch class in jQuery/JavaScript for active/inactive state
  • How To Track Outbound Clicks Using Javascript
  • How to get total seconds elapsed since the beginning of the month?
  • Protractor: Stale element reference at "browser.wait(EC.visibilityOf(confDial), FIFTY_SECONDS);"
  • Access to an array inside an object
  • Reseting an JavaScript Interval with different value?
  • Learning Angular for the first time - version 2 or 4?
  • Rendering RSS feed (XML) in React with jquery, why do object values parsed from the feed seem empty?
  • Node.js xml2js http.request tag matching
  • applying texture to custom plane geometry in Threejs
  • How do I pass an Event as a function parameter in HTML written inside JavaScript variable?
  • Interface of object parameter with default value and default property
  • Does using try / catch rather than `.catch` observable operator with XHR requests reduce performance?
  • In IE11 background colors not working on printing
  • TypeScript interface signature "(): string"
  • Is synchronous XMLHttpRequest supported in Internet Explorer 10 and 11?
  • Axios function not returning any values with js
  • How to use firestore TIMESTAMP to create time-stamp in JavaScript
  • Instantiate subclass without constructing
  • Outputing a created object in javascript to a server side JSON file
  • Transition the numeric labels in a bar chart
  • createBottomTabNavigator: hide just one tab from the tabBar
  • iife vs simple statement behavior with document.title
  • showDialogPopup Refresh Page after Click
  • Child component does not set the initial value passed from the parent: ReactJS
  • Nodejs javascript added to button not responding
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com