Управление DOM в метеоре

Я хочу знать о манипуляциях с DOM в метеоре. Мой код выглядит следующим образом:

    <template name = "studentList">

    {{#each}}
        <div class = "name">
            Name: {{this.name}}
        </div>

        <div class = "age">
            Age: {{this.age}}
        </div>
        <button class = "edit"> Edit </button>
    {{/each}}

    <button class = "addStudent"> Add Student </button>
</template>


Template.studentList.helpers({
    studentlist:function(){
        return Students.find();
    }
});

Template.studentList.events({
    //I am doing the DOM manupulation here based on the buttons clicked
});

Я получаю список информации о студентах из БД и отображаю их в шаблоне. Теперь для каждого ученика есть кнопка редактирования. Когда пользователь нажимает эту кнопку редактирования, я хочу изменить поле «имя» и «возраст» учащегося в виде текстового поля и дать возможность «сохранить» и «отменить».

Точно так же у меня есть кнопка «добавить ученика» в конце шаблона. Когда пользователь нажимает на нее, я хочу отобразить форму, в которой имя и возраст ученика добавляются, а затем сохраняются.

Пока что я могу это сделать, но очень наивно, используя много кода Jquery/Javascript в событиях studentList. Я читал много сообщений, в которых говорится, что это неправильный путь.

Может все-таки расскажите, как можно реализовать эту функцию в метеоре. Или просто к некоторым возможным способам сделать это.

Помощь приветствуется.


person Community    schedule 09.04.2015    source источник


Ответы (1)


Это возможный способ добиться этого.

Давайте попробуем сделать это шаг за шагом.

Во-первых, вот как должен выглядеть HTML.

{{#if  editName}} <!-- editName template helper -->
   <!-- If the Session is equal to true this part of the html will be showed -->
    <input type="text" class="newName" value="{{this.name}}" />
  {{else}}
    <!-- this is what we show by default on the view, if user click the div, the input will be showed -->
    <div class="name">Name: {{this.name}} </div>
{{/if}}

Теперь JS.

Помощник должен выглядеть так.

Template.studentList.helpers({tName:function(){
      return Session.get("studentName" + this._id); //getting the session true or false.
    }
});

И События.

Template.studentList.events({
  'click .name' : function(event,template){
     //On this event we are Setting the Session to true and holding the id of the student
     return Session.set("studentName" + this._id,true)
   },
   'keypress .newName':function(event,template){
      //Some keypress to update the value 
       //using http://docs.meteor.com/#/full/template_$ to get the value using meteor
       var newNameStudent = template.$('.newName').val();
       if(event.keyCode == 13){ //if enter lets update the value
           Students.update({_id:this._id},{$set:{name:newNameStudent}})
           return Session.set("studentName" + this._id,false) //setting to false the session to hide the input and show the <div>
         }
     },
     'click .cancel':function(){
        return Session.set("studentName" + this._id,false) //setting to false the session to hide the input and show the <div>
       }
  })

Если вы видите, что кода не так уж много (наверное), вы понимаете, как использовать сеансы для выполнения простых операций CRUD.

Я сделал Meteorpad этого рабочего примера, проверьте его.

person Ethaan    schedule 09.04.2015
comment
Я выполнил аналогичный шаг, описанный выше, самостоятельно, но все же я принимаю ваш ответ, так как это правильный путь :) - person ; 13.04.2015