iDev

[meteor.js] 텍스트를 더블 클릭하면 수정 가능하게 만들기

KraZYeom 2014. 8. 12. 22:12
반응형



원리는 아주 간단하다.

그냥 텍스트를 보여주다가, 더블 클릭을 하면 input의 value에 텍스트를 넣어주면 끗.

Deps.flush()가 중요하다. 변경된 DOM을 강제로 다시 그려서 input 필드를 자동으로 focus() 가능하게 해준다. 

이후, focusout 이벤트를 받아서 다시 그냥 텍스트로 보여주게 한다. 


sample.html

<head>
  <title>sample</title>
</head>

<body>
  {{> hello}}
</body>

<template name="hello">
  <h1>Hello World!</h1>
  {{#if editing}}
  <input type="text" id="edit-input" value="{{greeting}}"/>
  {{else}}
  <div id="greeting">{{greeting}}</div>
  {{/if}}
</template>


sample.js

if (Meteor.isClient) {
  Session.setDefault('key', null);

  Template.hello.greeting = function () {
    return "Welcome to sample.";
  };

  Template.hello.editing = function () {
    return Session.get("key");
  };

  Template.hello.events({
    'dblclick #greeting': function(e, tmpl) {
      Session.set("key", true);
      Deps.flush(); // force DOM redraw, so we can focus the edit field
      var input = tmpl.find("#edit-input");
      input.focus();
      input.select();
    },
    'focusout #edit-input' : function(e) {
      Session.set("key", false);
    }
  });
}

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup
  });
}


반응형